from datetime import datetime, timedelta
from apps.common.utils.response import response_message, response_success, response_action
from decimal import Decimal
import random
import json
from apps.common.utils.tools import random_num

from apps.pay.order.countAward.countPersonalAward import countPersonalAwardHandle
from apps.pay.order.countAward.countFranchiseeAward import countFranchiseeAward
from apps.pay.order.countAward.countProfit import countProfitFun, countProfitForFranchiseeFun
from apps.pay.order.dao import OrderDao
from apps.system.rank.dao import RankDao
from apps.merchant.sku.dao import SkuDao
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao
from apps.user.dao import UserDao

from apps.pay.order.payReturnHandle.upRank import upRankHandle
from apps.pay.order.payReturnHandle.buyItem import buyItemHandle
from apps.common.ali.sendSms.service import sendSmsForAli
from apps.chat.message.service import sendMessage
from apps.pay.order.payReturnHandle.incomesDeductionActivity import incomesDeductionActivityHandle
from apps.pay.order.payReturnHandle.expenseSendIncomesActivity import expenseSendIncomesActivityHandle
from apps.pay.order.payReturnHandle.dismantleOrderByItem import dismantleOrderByItemHandle
from apps.user.countVerticalData import updateVerticalPerformance
from apps.user.countTeamDate import updateTeamPerformance
from apps.user.countSelfData import updateSelfPerformance
from apps.chat.message.functions import MessageFun
from apps.pay.order.countAward.countTeamAward import countTeamAwardFun
from apps.pay.order.countAward.countTeamLevel import countTeamLevelFun
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.merchant.shop.dao import ShopDao
from apps.system.lessee.dao import LesseeDao
from apps.merchant.coupon.dao import CouponDao

# 设置实际支付价格
def setPayMoney(params, data, user):
    # print('设置实际支付金额', data.get('scene'), params.get('orderItemList'))
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection' or data.get('scene') == 'shopItem':
        costPrice = 0
        sellingPrice = 0
        marketPrice = 0
        realPayIncomes = 0
        discountParams = []
        for orderItem in params.get('orderItemList'):
            if orderItem.get('sku'):
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku:
                    costPrice = costPrice + sku.costPrice * orderItem.get('payCount')
                    sellingPrice = sellingPrice + sku.sellingPrice * orderItem.get('payCount')
                    marketPrice = marketPrice + sku.marketPrice * orderItem.get('payCount')
        # 计算优惠
        realPay = sellingPrice
        try:
            if data.get('scene') == 'shopItem':
                realPay = realPay
                discountParams = []
            else:
                item = ItemDao().findOneByObjId(orderItem.get('item'))
                if not item.tags.filter(key__contains='特价秒杀').exists():
                    if user:
                        # 优先使用抵扣积分
                        if user.incomesCredit > 0:
                            if user.incomesCredit < sellingPrice * Decimal(0.1):
                                realPay = sellingPrice - user.incomesCredit
                                discountParams.append({'type': '抵扣积分', 'money': str(user.incomesCredit)})
                            else:
                                realPay = Decimal(sellingPrice * Decimal(0.9)).quantize(Decimal("0.00"))
                                discountParams.append({'type': '抵扣积分', 'money': str(Decimal(sellingPrice-realPay))})

                        # 再使用立减券
                        if params.get('defaultDisCoupon'):
                            _coupon = CouponDao().findOneByObjId(params.get('defaultDisCoupon'))
                            if _coupon:
                                realPay = realPay - _coupon.fullMoney
                                discountParams.append({'type': '立减券', 'money': str(_coupon.fullMoney)})

        except Exception as e:
            realPay = realPay
        return {'status': 200, 'data': {
            'costPrice': str(Decimal(costPrice).quantize(Decimal("0.00"))),
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'marketPrice': str(Decimal(marketPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    elif data.get('scene') == 'recharge':
        costPrice = 0
        sellingPrice = params.get('realPay')
        realPay = params.get('realPay')
        realPayIncomes = 0
        discountParams = []
        return {'status': 200, 'data': {
            'costPrice': str(costPrice),
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    elif data.get('scene') == 'payForFranchisee':
        costPrice = 0
        sellingPrice = params.get('realPay')
        realPay = params.get('realPay')
        realPayIncomes = 0
        discountParams = []
        return {'status': 200, 'data': {
            'costPrice': str(costPrice),
            'sellingPrice': str(Decimal(sellingPrice).quantize(Decimal("0.00"))),
            'realPay': str(Decimal(realPay).quantize(Decimal("0.00"))),
            'realPayIncomes': str(Decimal(realPayIncomes).quantize(Decimal("0.00"))),
            'discountParams': discountParams
            }}
    else:
        print('支付场景不存在')
        return {'status': 500, 'data': response_message('支付场景不存在')}

# 随机立减
def random_sub(money, m, n):
    _random = random.uniform(m, n)
    if money > Decimal(_random):
        money = money - Decimal(_random)
    return money.quantize(Decimal("0.00"))



# 创建订单之前校验
def beforeCreateOrderScene(params, data, user):
    print('创建订单之前校验', params)
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection' or data.get('scene') == 'shopItem':
        # print('校验库存', params.get('orderItemList'))
        orderItemList = params.get('orderItemList')
        for orderItem in orderItemList:
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            # 检查限时抢购是否结束
            if item and item.tags.filter(key__contains='特价秒杀').exists():
                activityParams = json.loads(item.activityParams)
                endTime = datetime.strptime(activityParams.get('endTime'), "%Y-%m-%d %H:%M:%S")
                if endTime < datetime.now():
                    return {'status': 500, 'data': response_message('特价秒杀活动已结束')}
                # 检查购买个数
                if orderItem.get('payCount') > 1:
                    return {'status': 500, 'data': response_message('特价秒杀商品只能单个购买')}
                # 检查检查一个人只能下一单，如果当前在当天的15点之前，判断如果用户的limitedTimeKillTime在前一天15点到当天15点之间，如果在，则不允许下单
                if user.limitedTimeKillTime:
                    if datetime.now().hour < 15:
                        if user.limitedTimeKillTime > (datetime.now().replace(hour=15, minute=0, second=0, microsecond=0) - timedelta(days=1)) and user.limitedTimeKillTime < datetime.now():
                            return {'status': 500, 'data': response_message('您已经参与过本期特价秒杀活动')}
                    else:
                        if user.limitedTimeKillTime > (datetime.now().replace(hour=15, minute=0, second=0, microsecond=0)) and user.limitedTimeKillTime < datetime.now():
                            return {'status': 500, 'data': response_message('您已经参与过本期特价秒杀活动')}

            # 检验是否上架
            if item and item.status == 0:
                return {'status': 500, 'data': response_message('商品' + item.name + '暂未上架')}
            if item and orderItem.get('sku') and item.isCheckStock:
                # 校验sku库存
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku.stock < orderItem.get('payCount'):
                    return {'status': 500, 'data': response_message('库存不足')}
    elif data.get('scene') == 'recharge':
        return {'status': 200, 'data': {}}
    elif data.get('scene') == 'payForFranchisee':
        return {'status': 200, 'data': {}}
    else:
        return {'status': 500, 'data': response_message('支付场景不存在')}
    return {'status': 200, 'data': {}}

# 创建订单
def createOrderScene(params, data, user):
    if data.get('scene') == 'generay' or data.get('scene') == 'giftSection' or data.get('scene') == 'shopItem':
        
        orderItemList = params.get('orderItemList')
        for orderItem in orderItemList:
            # 计算利润
            sku = SkuDao().findOneByObjId(orderItem.get('sku'))
            if data.get('scene') == 'generay' or data.get('scene') == 'shopItem':
                if sku.item.shop.types == '0':
                    if sku.item.activity:
                        res = countProfitFun({'sellingPrice': sku.sellingPrice, 'costPrice': sku.costPrice, 'itemId': sku.item.id, 'scene': 'generay', 'payCount': orderItem.get('payCount')})
                        orderItem.update(res)
                elif sku.item.shop.types == '1':
                    res = countProfitForFranchiseeFun({'sellingPrice': sku.sellingPrice, 'costPrice': sku.costPrice, 'itemId': '', 'scene': 'shopItem'})
                    orderItem.update(res)
            elif data.get('scene') == 'giftSection':
                if sku.item.activity:
                    res = countProfitFun({'sellingPrice': sku.sellingPrice, 'costPrice': sku.costPrice, 'itemId': sku.item.id, 'scene': 'giftSection'})
                    orderItem.update(res)
            # 追加成本价
            priceModel = {}
            priceModel['sellingPrice'] = str(sku.sellingPrice)
            priceModel['costPrice'] = str(sku.costPrice)
            # 计算实付
            realPay = (sku.sellingPrice/Decimal(data.get('sellingPrice'))) * Decimal(data.get('realPay'))
            priceModel['realPay'] = str(realPay.quantize(Decimal('0.00')))
            orderItem.update({"priceModel": priceModel})
            # 商户
            if sku.item.shop:
                orderItem['shop'] = sku.item.shop.id
        data['content'] = json.dumps({'orderItemList': orderItemList, 'discountParams':data.get('discountParams'), 'coupon': params.get('defaultDisCoupon')})

        _order = OrderDao().create(data)
        # 创建订单成功之后，减少库存
        content = json.loads(_order.content)
        for orderItem in content.get('orderItemList'):
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            # 减少库存
            if item and orderItem.get('sku'):
                if orderItem.get('sku') and item.isCheckStock:
                    SkuDao().subStock(orderItem.get('sku'), orderItem.get('payCount'))
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    elif data.get('scene') == 'recharge':
        content = {'orderItemList': []}
        data['content'] = json.dumps(content)
        _order = OrderDao().create(data)
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    elif data.get('scene') == 'payForFranchisee':
        shop = ShopDao().findOneByObjId(params.get('shopId'))
        lessee = LesseeDao().getLessee()
        content = {'orderItemList': []}
        content['shopUserId'] = shop.user.id
        content['shopParentId'] = shop.user.parent.id if shop.user.parent else ''
        content['discountsRate'] = str(shop.discountsRate)
        content['franchiseeParams'] = lessee.franchiseeParams
        data['content'] = json.dumps(content)
        _order = OrderDao().create(data)
        return {'status': 200, 'data': response_success({'orderId': _order.orderId})}
    else:
        return response_message('支付场景不存在')


# 支付成功返回
def payReturnScene(payway, orderId, transactionId='', thirdName='', lzOrderId=''):
    _order = OrderDao().findOneByOrderId(orderId)
    if not _order:
        return response_message('订单不存在')
    if _order.scene == 'generay' or _order.scene == 'giftSection' or _order.scene == 'shopItem':
        if _order.orderStatus == 'WAIT_PAY' or _order.orderStatus == 'CANCEL':
            print('商品购买处理')
            data = {}
            data['orderStatus'] = 'WAIT_SEND'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            data['thirdName'] = thirdName
            data['transactionId'] = lzOrderId
            # 机器人订单直接完成
            if _order.user.isRobot:
                data['orderStatus'] = 'FINISH'
            _order = OrderDao().update(_order.id, data)
            if _order.scene == 'generay' or _order.scene == 'giftSection':
                # 扣除用户抵扣积分
                subIncomesCredit(_order)
            # 统计自己的业绩
            updateSelfPerformance('add', _order.user, 1, _order.sellingPrice)
            # 给用户升级
            _user = UserDao().findOneByObjId(_order.user.id)
            if _user.selfPerformance >= 100:
                UserDao().addRank(_order.user, 1)
            if _user.selfPerformance >= 2000:
                UserDao().addRank(_order.user, 2)
            # 检查上级级别
            UserDao().checkParentRank(_order.user)
            # 发放个人奖励
            sendContributionValues = countPersonalAwardHandle(_order)
            # 发放团队奖励
            countTeamAwardFun(_order, sendContributionValues)
            # 计算团队级别
            countTeamLevelFun(_order)
            # 给用户发送订单信息
            if _order.addrinfo:
                addrinfoDict = json.loads(_order.addrinfo)
                MessageFun().sendMessage(None, _order.user, 'jytz', {'title': '订单通知', 'content': '您已支付成功，收货地址为'+addrinfoDict.get('addrInfo')})
            # 处理购买商品后销量库存等信息
            buyItemHandle(_order)
            # 拆单
            dismantleOrderByItemHandle(_order)
            # 新增特价秒杀记录
            content = json.loads(_order.content)
            if content.get('orderItemList') and len(content.get('orderItemList'))>0:
                for orderItem in content.get('orderItemList'):
                    item = ItemDao().findOneByObjId(orderItem.get('item'))
                    if item and item.tags.filter(key__contains='特价秒杀').exists():
                        UserDao().update(_order.user.id, {'limitedTimeKillTime': datetime.now()})

    elif _order.scene == 'recharge':
        if _order.orderStatus == 'WAIT_PAY' or _order.orderStatus == 'CANCEL':
            print('充值处理')
            data = {}
            data['orderStatus'] = 'FINISH'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            _order = OrderDao().update(_order.id, data)
            # 增加购物积分
            money = _order.sellingPrice
            payway = 'incomes'
            UserDao().addWallet(payway, _order.user, money)
            data = {}
            data['scene'] = 'inMoney'
            data['user'] = _order.user.id
            data['fromUser'] = _order.user.id
            data['orderId'] = _order.orderId
            data['money'] = money
            data['payway'] = payway
            data['changeWay'] = 'add'
            data['orderStatus'] = 'FINISH'
            RecordIncomesDao().create(data)
    elif _order.scene == 'payForFranchisee':
        if _order.orderStatus == 'WAIT_PAY' or _order.orderStatus == 'CANCEL':
            print('加盟商收款处理')
            data = {}
            data['orderStatus'] = 'FINISH'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            data['transactionId'] = transactionId
            _order = OrderDao().update(_order.id, data)
            # 统计自己的业绩
            updateSelfPerformance('add', _order.user, 1, _order.sellingPrice)
            # 给用户升级
            _user = UserDao().findOneByObjId(_order.user.id)
            if _user.selfPerformance >= 100:
                UserDao().addRank(_order.user, 1)
            if _user.selfPerformance >= 2000:
                UserDao().addRank(_order.user, 2)
            # 检查上级级别
            UserDao().checkParentRank(_order.user)
            # 发放加盟店分红
            sendContributionValues = countFranchiseeAward(_order)
            # 发放团队奖励
            countTeamAwardFun(_order, sendContributionValues)
            # 计算团队级别
            countTeamLevelFun(_order)
            # 给用户发送订单信息
            if _order.addrinfo:
                addrinfoDict = json.loads(_order.addrinfo)
                MessageFun().sendMessage(None, _order.user, 'jytz', {'title': '订单通知', 'content': '您已支付成功，收货地址为'+addrinfoDict.get('addrInfo')})
            # 处理购买商品后销量库存等信息
            buyItemHandle(_order)
            # 拆单
            dismantleOrderByItemHandle(_order)


# 取消订单返回
def cancelOrderReturnScene(orderId):
    order = OrderDao().findOneByOrderId(orderId)
    # 返还库存 和 扣除销量
    content = json.loads(order.content)
    if order.scene == 'generay' or order.scene == 'giftSection' or order.scene == 'shopItem':
        for item in content.get('orderItemList'):
            if item.get('sku'):
                ItemDao().subSales(item.get('item'), item.get('payCount'))
                SkuDao().addStock(item.get('sku'), item.get('payCount'))
                SkuDao().subSales(item.get('sku'), item.get('payCount'))
    elif order.scene == 'guest':
        return


# 扣除用户抵扣积分
def subIncomesCredit(order):
    content = json.loads(order.content)
    if content.get('orderItemList') and len(content.get('orderItemList'))>0:
        for orderItem in content.get('orderItemList'):
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            if item.tags.filter(key__contains='特价秒杀').exists():
                return

    user = UserDao().findOneByObjId(order.user.id)
    realUser = user
    if order.anotherUser:
        realUser = order.anotherUser
    
    realPay = order.sellingPrice
    if realUser.incomesCredit > 0:
        money = 0
        if realUser.incomesCredit <= order.sellingPrice * Decimal(0.1):
            realPay = order.sellingPrice - realUser.incomesCredit
            money = realUser.incomesCredit
            realUser.incomesCredit = 0
            realUser.save()
        else:
            realPay = Decimal(order.sellingPrice * Decimal(0.9)).quantize(Decimal("0.00"))
            realUser.incomesCredit = realUser.incomesCredit - order.sellingPrice * Decimal(0.1)
            money = order.sellingPrice * Decimal(0.1)
            realUser.save()

        # 扣除用户抵扣积分
        data = {}
        data['scene'] = 'expense'
        data['user'] = realUser.id
        data['fromUser'] = realUser.id
        data['orderId'] = order.orderId
        data['money'] = Decimal(money).quantize(Decimal('0.00'))
        data['payway'] = 'incomesCredit'
        data['changeWay'] = 'sub'
        RecordIncomesDao().create(data)